
import { BadRequestException, HttpException, HttpStatus, Injectable, PipeTransform } from "@nestjs/common";
import { ErrorResponse } from "src/common/types/common.type";

export class InvalidIntegerException extends HttpException {
    constructor(value: any) {
        super(`Parameter: "${value}" is not an integer.`, HttpStatus.BAD_REQUEST);
    }
}

@Injectable()
export class IntValidationPipe implements PipeTransform {
    transform(value: any) {
        const isInt = (val: any): boolean => {
            if (val == null) return false;
            const num = Number(val);
            return Number.isInteger(num) && !isNaN(num);
        };

        if (!isInt(value)) {
            /***
             * Throw new HttpException("error message", HttpStatus.BAD_REQUEST)
             * So global HttpExceptionFilter can catch this exception.
             */
            throw new InvalidIntegerException(value);
        }
        return Number(value);
    }
}